#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2022-2-21 16:03
# @Author : huabao.tan
# @File : test.py
# @Software: PyCharm
import requests
import tkinter as tk
from tkinter import filedialog


class downloadPicture:

    def __init__(self, work):
        self.work = work

    def save_file(self):
        root = tk.Tk()
        root.withdraw()
        Fpath = filedialog.asksaveasfilename()
        return Fpath

    def header(self):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'}
        return headers

    def params(self, page=10, work='',width=None, height=None):
        if work=='':
            work=self.work
        pn = 1
        params = {
            'tn': 'resultjson_com',
            'logid': '8846269338939606587',
            'ipn': 'rj',
            'ct': '201326592',
            'is': '',
            'fp': 'result',
            'queryWord': '%s' % work,
            'cl': '2',
            'lm': '-1',
            'ie': 'utf-8',
            'oe': 'utf-8',
            'adpicid': '',
            'st': '-1',
            'z': '',
            'ic': '',
            'hd': '',
            'latest': '',
            'copyright': '',
            'word': '%s' % work,
            's': '',
            'se': '',
            'tab': '',
            'width': '%s' % width,
            'height': '%s' % height,
            'face': '0',
            'istype': '2',
            'qc': '',
            'nc': '1',
            'fr': '',
            'expermode': '',
            'force': '',
            'cg': 'girl',
            'pn': pn,  # 从第几张图片开始
            'rn': '30',
            'gsm': '1e',
        }
        return params

    def url(self):
        url = 'https://image.baidu.com/search/acjson?'
        return url

    def result(self):
        response = requests.get(url=self.url(), headers=self.header(), params=self.params())
        response.encoding = 'utf-8'
        response = response.json()
        info_list = response['data']
        del info_list[-1]
        img_path_list = []
        for i in info_list:
            img_path_list.append(i['thumbURL'])

        for img_path in img_path_list:
            img_data = requests.get(url=img_path, headers=self.header()).content

            return img_data

    def download(self):
        file_path = self.save_file()
        img_path = file_path + self.work + '.jpg'
        with open(img_path, 'wb') as f:
            print('正在下载中， 文件路径为%s' % img_path)
            f.write(self.result())


if __name__ == '__main__':
    d = downloadPicture('鞠婧祎')
    # print(d.result())
    d.download()
